﻿using System;
using System.Collections;
using System.Collections.Generic;
using Server.Core.Reflection;

namespace Server.Core.Serialization.BooMessaging.Contracts
{
    public class BooCollectionContract : BooContract
    {
        private readonly BooContract _elementContract;
        private readonly bool _elementIsPackage;

        public BooCollectionContract(Type type)
            : base(type)
        {
            var args = ReflectionUtils.GetGenericArguments(type, typeof(ICollection<>));
            if (args == null)
            {
                var msg = string.Format("The type {0} is not a generic collection type.", type);
                throw new BooContractException(msg);
            }

            var elementType = args[0];
            _elementContract = BooContractResolver.ResolveContract(elementType);
            _elementIsPackage = _elementContract.IsPackage;
        }

        public override bool IsPackage
        {
            get { return true; }
        }

        protected override void DoWrite(BooMessageWriter writer, object obj)
        {
            if (_elementIsPackage)
            {
                foreach (var item in (IEnumerable)obj)
                {
                    writer.StartPackage();
                    _elementContract.Write(writer, item);
                    writer.EndPackage();
                }
            }
            else
            {
                foreach (var item in (IEnumerable)obj)
                {
                    _elementContract.Write(writer, item);
                }
            }
        }
    }
}
